from flask import Blueprint, request, jsonify, render_template
import re
import os
import time
from datetime import datetime

# 代码存储目录
CODE_STORAGE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'data', 'code_snippets')
os.makedirs(CODE_STORAGE_DIR, exist_ok=True)

code_mirror_bp = Blueprint('code_mirror', __name__)

@code_mirror_bp.route('/', methods=['GET'])
def index():
    return render_template("code_mirror.html")

def detect_language(content):
    """根据代码内容自动检测编程语言"""
    if re.search(r'^\s*(import|from|def|class)\s', content):
        return 'python'
    elif re.search(r'^\s*(function|let|const|var|=>)\s', content):
        return 'javascript'
    elif re.search(r'^\s*(public|class|void|int|String)\s', content):
        return 'java'
    elif re.search(r'^\s*[{}\[\]]', content):
        return 'json'
    return 'python'  # 默认返回python

@code_mirror_bp.route('/get-content', methods=['GET'])
def get_content():
    """获取编辑器当前内容"""
    return jsonify({
        'content': request.args.get('content', ''),
        'language': request.args.get('language', 'python')
    })

@code_mirror_bp.route('/set-content', methods=['POST'])
def set_content():
    """设置编辑器内容"""
    data = request.json
    content = data.get('content', '')
    language = data.get('language') or detect_language(content)
    
    return jsonify({
        'status': 'success',
        'content': content,
        'language': language
    })

# 示例代码存储
sample_codes = {
    'python': '''def hello_world():
    print("Hello, World!")''',
    'javascript': '''function helloWorld() {
    console.log("Hello, World!");
}''',
    'json': '''{
    "message": "Hello, World!"
}''',
    'java': '''public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}'''
}

def save_code_to_file(content, language):
    """保存代码到文件"""
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = f"{timestamp}_{language}.txt"
    filepath = os.path.join(CODE_STORAGE_DIR, filename)
    
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(content)
    
    return filename

def load_code_from_file(filename):
    """从文件加载代码"""
    filepath = os.path.join(CODE_STORAGE_DIR, filename)
    if not os.path.exists(filepath):
        return None
    
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    
    return content

@code_mirror_bp.route('/api/code', methods=['GET', 'POST'])
def handle_code():
    """处理代码保存和加载"""
    if request.method == 'POST':
        # 保存代码
        data = request.json
        content = data.get('content', '')
        language = data.get('language', 'python')
        
        if not content:
            return jsonify({'status': 'error', 'message': '内容不能为空'}), 400
        
        filename = save_code_to_file(content, language)
        return jsonify({
            'status': 'success',
            'filename': filename,
            'message': '代码保存成功'
        })
    else:
        # 加载代码
        filename = request.args.get('filename')
        if not filename:
            return jsonify({'status': 'error', 'message': '缺少文件名参数'}), 400
        
        content = load_code_from_file(filename)
        if content is None:
            return jsonify({'status': 'error', 'message': '文件不存在'}), 404
        
        return jsonify({
            'status': 'success',
            'content': content,
            'filename': filename
        })
